package lily.phs.urh;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import lily.phs.database.Constants;
import lily.phs.object.HealthTest;
import lily.phs.object.HereTipa;
import lily.phs.object.HospitalHistory;
import lily.phs.object.HuiZhenRecord;
import lily.phs.object.JieZhenRecord;
import lily.phs.object.MedicateRecord;
import lily.phs.object.ModuleSelect;
import lily.phs.object.NonimmuneVaccineHistory;
import lily.phs.object.PersonInfo;
import lily.phs.object.SickbedHistory;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class BuildProfile extends Activity implements OnClickListener,
		Constants {
	
	private ScrollLayoutView root;
	private ImageView ivDot1,ivDot2;
	private Button btn_confirm,btn_back,btnUpload;
	private ProgressDialog mpDialog;
	
	private BuilderView_1 view_1;
	private BuilderView_2 view_2;
	private SharedPreferences info;
	private String buildName;
	private int buildId;
	
	public Handler mHandler = new Handler(){
		@Override
    	public void handleMessage(Message msg) {
    		
    		super.handleMessage(msg);
    		refreshDots(msg.what);
		}
	};

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.buide_profile);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.i_title_2);
		
		info = getSharedPreferences(USERINFO,Context.MODE_PRIVATE);
		
		TextView tvTitle = (TextView)findViewById(R.id.title);
		tvTitle.setText("新建居民健康档案");
		
		btn_back = (Button) findViewById(R.id.title_left_btn);
        btn_back.setText("后退");
        btn_back.setOnClickListener(this);
        btn_confirm = (Button) findViewById(R.id.title_right_btn);
        btn_confirm.setText("保存");
        btn_confirm.setOnClickListener(this);
        btnUpload = (Button) findViewById(R.id.title_right_btn2);
        btnUpload.setText("上传");
        Button rightBtn0 = (Button) findViewById(R.id.title_right_btn0);
        rightBtn0.setVisibility(View.GONE);
        
        root = (ScrollLayoutView)this.findViewById(R.id.scroll);
        view_1 = new BuilderView_1(this);
        view_2 = new BuilderView_2(this);
        root.addView(view_1);
        root.addView(view_2);
        root.setToScreen(0);
        
        ivDot1 = (ImageView)this.findViewById(R.id.iv_dot1);
        ivDot2 = (ImageView)this.findViewById(R.id.iv_dot2);
	}

	/**
	 * 刷新绿点显示条
	 * @param index
	 */
	protected void refreshDots(int index) {
		// TODO Auto-generated method stub
		switch(index){
		case 0:{
			ivDot1.setImageResource(R.drawable.dot_green);
			ivDot2.setImageResource(R.drawable.dot_gray);
			break;
		}
		case 1:{
			ivDot1.setImageResource(R.drawable.dot_gray);
			ivDot2.setImageResource(R.drawable.dot_green);
			break;
		}
		}
	}

	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		if(view==btn_confirm){
			boolean integrity = view_1.checkIntegrity();
			if(integrity){
				mpDialog = new ProgressDialog(BuildProfile.this);  
				mpDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//设置风格为圆形进度条  
				mpDialog.setMessage("正在新建档案...");  
				mpDialog.setIndeterminate(false);//设置进度条是否为不明确  
				mpDialog.setCancelable(true);//设置进度条是否可以按退回键取消  
				mpDialog.show();
				new BuildThread().start();
			}
		}
		if(view==btnUpload){
			
		}
		else if(view==btn_back){
			new AlertDialog.Builder(this)
			.setIcon(android.R.drawable.ic_dialog_alert)
			.setMessage("当前的档案还未成功创建，您确定要舍弃这份档案并退出吗？")
			.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
//					startActivity(new Intent(BuildProfile.this, PeopleList.class));
					finish();
					overridePendingTransition(R.anim.anim_slide_in_left,R.anim.anim_slide_out_right);
				}
			})
			.setNegativeButton("取消", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					
				}
			})
			.create().show();
			
		}

	}
	
	class BuildThread extends Thread{
		public void run(){  
        	Message msg = handler.obtainMessage();
	        try{   
	        	Looper.getMainLooper();
	        	sleep(100); 
	        	createProfile();
	        	msg.what=11;
			}  
		    catch (Exception e){
		    	msg.what = 12;
		        e.printStackTrace();  
		    }  

        	handler.sendMessage(msg);
		}
	}
	
	private Handler handler = new Handler(Looper.getMainLooper()){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			if(msg.what==11){
				mpDialog.cancel();
				Intent intent = new Intent();
				Bundle bd = new Bundle();
				bd.putString("build_name", buildName);
				bd.putInt("build_id", buildId);
				intent.putExtras(bd);
				intent.setClass(BuildProfile.this, PeopleList.class);
				setResult(RESULT_OK,intent);
				finish();
				overridePendingTransition(R.anim.anim_slide_in_left,R.anim.anim_slide_out_right);
			}
			else if(msg.what==12){
				mpDialog.cancel();
				Toast.makeText(BuildProfile.this, "创建失败，请稍后重试。。。", Toast.LENGTH_LONG).show();
			}
		}
		
	};
	
	/**
	 * 本地创建档案
	 */
	private void createProfile(){
		String s = String.valueOf(System.currentTimeMillis());
		int pro = Integer.valueOf(s.substring(7));
		
		System.out.println("档案编号："+pro);
		buildId = pro;
		HereTipa ht = new HereTipa(this);
		ht.setHeti_here_id("暂未给定");
		ht.setHeti_profileid(pro);
		ht.setHeti_town_name(getResources().getString(R.string.def_rural));
		ht.setHeti_vico_name(info.getString("def_village","")+"村委会");
		ht.setHeti_buil_unit(getResources().getString(R.string.def_rural)+info.getString("def_village",""));
		ht.setHeti_buil_per(info.getString("operator_name",""));
		ht.setHeti_doctor(info.getString("operator_name",""));
		Date date = new Date(System.currentTimeMillis());
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		ht.setHeti_buil_date(sf.format(date));
		ht.insertHereTipa();
		PersonInfo pi = new PersonInfo(this);
		pi.setPein_profile_id(pro);
		pi.insertPersonInfo();
		
		view_1.setProfileid(pro);
		view_1.saveViews();
		buildName = view_1.getName();
		view_2.setProfileid(pro);
		view_2.saveViews();
		//体检表
		HealthTest htt=new HealthTest(getBaseContext());
		htt.setHete_profileid(pro);
		htt.setHete_testid(1);//第一次体检???
		htt.insertHealthTest();
		
		//住院史---限填2项
		HospitalHistory hh = new HospitalHistory(getBaseContext());
		hh.setHohi_profileid(pro);
		hh.setHohi_testid(1);
		hh.setHohi_id(1);
		hh.insertHospitalHistory();
		hh.setHohi_profileid(pro);
		hh.setHohi_testid(1);
		hh.setHohi_id(2);
		hh.insertHospitalHistory();
		//病床史---限填2项
		SickbedHistory sh = new SickbedHistory(getBaseContext());
		sh.setSihi_profileid(pro);
		sh.setSihi_testid(1);
		sh.setSihi_id(1);
		sh.insertSickbedHistory();
		sh.setSihi_profileid(pro);
		sh.setSihi_testid(1);
		sh.setSihi_id(2);
		sh.insertSickbedHistory();
		//吃药信息---限填6项
		MedicateRecord mr = new MedicateRecord(getBaseContext());
		mr.setMere_profileid(pro);
		mr.setMere_testid(1);
		mr.setMere_id(1);
		mr.insertMedicateRecord();
		mr.setMere_profileid(pro);
		mr.setMere_testid(1);
		mr.setMere_id(2);
		mr.insertMedicateRecord();
		mr.setMere_profileid(pro);
		mr.setMere_testid(1);
		mr.setMere_id(3);
		mr.insertMedicateRecord();
		mr.setMere_profileid(pro);
		mr.setMere_testid(1);
		mr.setMere_id(4);
		mr.insertMedicateRecord();
		mr.setMere_profileid(pro);
		mr.setMere_testid(1);
		mr.setMere_id(5);
		mr.insertMedicateRecord();
		mr.setMere_profileid(pro);
		mr.setMere_testid(1);
		mr.setMere_id(6);
		mr.insertMedicateRecord();
		//非免疫预防接种---限填3项
		NonimmuneVaccineHistory nvh = new NonimmuneVaccineHistory(getBaseContext());
		nvh.setNovh_profileid(pro);
		nvh.setNovh_testid(1);
		nvh.setNovh_id(1);
		nvh.insertNonimmuneVaccineHistory();
		nvh.setNovh_profileid(pro);
		nvh.setNovh_testid(1);
		nvh.setNovh_id(2);
		nvh.insertNonimmuneVaccineHistory();
		nvh.setNovh_profileid(pro);
		nvh.setNovh_testid(1);
		nvh.setNovh_id(3);
		nvh.insertNonimmuneVaccineHistory();
		
		ModuleSelect ms=new ModuleSelect(getBaseContext());
		ms.setMose_profile_id(pro);
		ms.setMose_health_record_id(1);
		ms.insertModuleSelect();
		JieZhenRecord jzr=new JieZhenRecord(getBaseContext());
		jzr.setThre_profileid(pro);
		jzr.setThre_state(1);
		jzr.insertJieZhenRecord();
		HuiZhenRecord hzr=new HuiZhenRecord(getBaseContext());
		hzr.setCore_profileid(pro);
		hzr.setCore_state(1);
		hzr.insertHuiZhenRecord();
		
	}
	
	/**
	 * 新建时使用999999为临时档案编号，在本地临时建立表；
	 * ---本地表中档案编号是int,最大长度8位，无法存储18位
	 * 同时将数据提交到远程数据库，并获得回传的档案编号，最后更新本地数据库
	 */
	private void createProfileToServer(){
		
		int pro=999999;
		System.out.println("档案编号："+pro);
		
		HereTipa ht=new HereTipa(getBaseContext());
		ht.setHeti_profileid(pro);
		ht.insertHereTipa();
		PersonInfo pi=new PersonInfo(getBaseContext());
		pi.setPein_profile_id(pro);
		pi.insertPersonInfo();
		
		view_1.setProfileid(pro);
		view_1.saveViews();
		view_2.setProfileid(pro);
		view_2.saveViews();
		
		HereTipa ht1 = new HereTipa(this);
		ht1.selectHereTipa(pro);
		PersonInfo pi1 = new PersonInfo(this);
		pi1.selectPersonInfo(pro);
		
		//提交到服务器，并获得回传的档案标号
		JSONObject data= new JSONObject();
		try{
			data.put("建档人员姓名", info.getString("operator_name",""));
			data.put("建档人员ID", info.getString("operator_id",""));
			data.put("标示符", info.getString("org_code",""));//"29EE43D6");
			
			data.put("姓名", ht1.getHeti_name());
			data.put("档案编号（区域码）", info.getString("area_code",""));
					//"640381105204");
			data.put("建档机构编码", info.getString("org_key",""));
			data.put("性别", ""+pi1.getPein_sex());
			data.put("出生日期", pi1.getPein_born());
//			data.put("出生日期", "2011-11-11");//仅当前测试使用
			data.put("身份证号", pi1.getPein_perid());
			String temp = pi1.getPein_work();
			if(temp.length()==0){
				data.put("工作单位", "null");
			}else{
				data.put("工作单位", temp);
			}
			temp = pi1.getPein_phone();
			if(temp.length()==0){
				data.put("本人电话", "null");
			}
			else{
				data.put("本人电话", temp);
			}
			temp = pi1.getPein_contact_name();
			if(temp.length()==0){
				data.put("联系人姓名", "null");
			}
			else{
				data.put("联系人姓名", temp);
			}
			temp = pi1.getPein_contact_phone();
			if(temp.length()==0){
				data.put("联系人电话", "null");
			}
			else {
				data.put("联系人电话", temp);
			}
			
			data.put("常住类型", ""+pi1.getPein_permatent_type());
			
			data.put("民族", pi1.getNation());
			data.put("血型", ""+pi1.getPein_blood_type());
			data.put("RH阴性", ""+pi1.getPein_rh_negative());
			data.put("文化程度", ""+pi1.getPein_culture_stdd());
			data.put("职业", ""+pi1.getPein_occupation());
			data.put("婚姻状况", ""+pi1.getPein_marriage());
			
			data.put("地址", ht1.getHeti_now_addr());
			data.put("组编码", ht1.getAddressGroup());
    		data.put("籍贯", getResources().getString(R.string.def_area_code));//"640381");
    		data.put("户籍地组编码", ht1.getHhGroup());
    		data.put("出生地",getResources().getString(R.string.def_area_code));//"640381");
    		data.put("户籍地",info.getString("area_code",""));//"640381107206");
			
			data.put("医疗费用支付方式（编码）", pi1.getPein_hos_cost_type());
			data.put("其他支付方式", pi1.getPein_hos_cost_type_ot());
			data.put("药物过敏史（编码）", pi1.getPein_drug_allergy());
			data.put("其他过敏史", pi1.getPein_drug_allergy_ot());
			data.put("暴露史", pi1.getPein_exposure_his());
			data.put("既往史（疾病）", pi1.getPein_disease());
			data.put("既往史（其他疾病）", pi1.getPein_disease_ot());
			data.put("既往史（疾病时间）", pi1.getPein_disease_date());
			data.put("既往史（有无手术）", pi1.getPein_surgery());
			data.put("既往史（手术1）", pi1.getPein_surgery_name1());
			data.put("既往史（手术1时间）", pi1.getPein_surgery_date1());
			data.put("既往史（手术2）", pi1.getPein_surgery_name2());
			data.put("既往史（手术2时间）", pi1.getPein_surgery_date2());
			data.put("既往史（有无外伤）", pi1.getPein_trauma());
			data.put("既往史（外伤1）", pi1.getPein_trauma_name1());
			data.put("既往史（外伤1时间）", pi1.getPein_trauma_time1());
			data.put("既往史（外伤2）", pi1.getPein_trauma_name2());
			data.put("既往史（外伤2时间）", pi1.getPein_trauma_time2());
			data.put("既往史（有无输血）", pi1.getPein_transfusion());
			data.put("既往史（输血1）", pi1.getPein_trfusion_reason1());
			data.put("既往史（输血1时间）", pi1.getPein_trfusion_time1());
			data.put("既往史（输血2）", pi1.getPein_trfusion_reason2());
			data.put("既往史（输血2时间）", pi1.getPein_trfusion_time2());
			
			data.put("家族史（父亲）", pi1.getPein_family_his_ft());
			data.put("家族史（父亲其他疾病）", pi1.getPein_family_his_ft_ot());
			data.put("家族史（母亲）", pi1.getPein_family_his_mt());
			data.put("家族史（母亲其他疾病）", pi1.getPein_family_his_mt_ot());
			data.put("家族史（兄妹）", pi1.getPein_family_his_bs());
			data.put("家族史（兄妹其他疾病）", pi1.getPein_family_his_bs_ot());
			data.put("家族史（子女）", pi1.getPein_family_his_sd());
			data.put("家族史（子女其他疾病）", pi1.getPein_family_his_sd_ot());
			data.put("有无遗传病史", pi1.getPein_hereditary_his());
			data.put("遗传病名称", pi1.getPein_hereditary_name());
			data.put("残疾情况（编码）", pi1.getPein_disable_situ());
			data.put("残疾情况（其他残疾）", pi1.getPein_disable_situ_ot());
			data.put("生活环境（排风）", ""+pi1.getPein_live_kit());
			data.put("生活环境（燃料）", ""+pi1.getPein_live_fuel());
			data.put("生活环境（饮水）", ""+pi1.getPein_live_water());
			data.put("生活环境（厕所）", ""+pi1.getPein_live_toilet());
			data.put("生活环境（禽畜栏）", ""+pi1.getPein_live_stock());
			data.put("责任医生编码", info.getString("doctor_key",""));
		}
		catch(JSONException e){
			e.printStackTrace();
		}
		String sData = data.toString();
		try {
			Log.i("upload","person info="+data.toString(2));
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			Log.i("upload","person info="+sData);
			e.printStackTrace();
		}
		
		Message message = handler.obtainMessage();
		try {
			String pathUrl = getResources().getString(R.string.url_person_info);
			URL url = new URL(pathUrl);
			HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
			httpConn.setDoOutput(true);
			httpConn.setDoInput(true);
			httpConn.setUseCaches(false);
			httpConn.setRequestMethod("POST");

			byte[] requestStringBytes = sData.getBytes();
			httpConn.setRequestProperty("Content-length", "" + requestStringBytes.length);
			httpConn.setRequestProperty("Content-Type", "application/octet-stream");
			httpConn.setRequestProperty("Connection", "Keep-Alive");
			httpConn.setRequestProperty("Charset", "UTF-8");				
			
			OutputStream outputStream=httpConn.getOutputStream();
			Log.i("upload", "httpConnection established");
			outputStream.write(requestStringBytes);
			outputStream.flush();
			outputStream.close();	
			
			int responseCode = httpConn.getResponseCode();
			if (HttpURLConnection.HTTP_OK == responseCode){
				Log.i("upload", "httpConnection responsecode ok");
			}
			InputStreamReader in = new InputStreamReader(httpConn.getInputStream(),"UTF-8");
			BufferedReader buffer = new BufferedReader(in);
			String result = "";
			String inputLine = null;
			while(((inputLine=buffer.readLine())!=null)){
				result+=inputLine;
			}
			buffer.close();
			httpConn.disconnect();
			
			String code = "";//返回的档案编码
			if(result!=null&&result.length()>0){
				Log.i("upload", "result="+result);
				JSONObject json = new JSONObject(result);
				code = json.getString("record_code");
				Log.i("upload", "code="+code);
				
				updateHealthRecord(code);
				message.what = 11;//提交成功,并得到档案编号
			}
			else{
				message.what = 12;//未成功提交
				ht.delectHereTipa(pro);
				pi.deletePersonInfo(pro);
			}
		} 
		catch (Exception ex){
			message.what = 12;//未成功提交
			ht.delectHereTipa(pro);
			pi.deletePersonInfo(pro);
			Log.e("upload", "upload failed...");
			ex.printStackTrace();
		}
		finally{
			handler.sendMessage(message);			
		}
		
	}

	/**
	 * 根据recordid更新数据库
	 * @param recordid 档案编号
	 */
	private void updateHealthRecord(String recordid) {
		// TODO Auto-generated method stub
		int preId = 999999;
		String id = recordid;//18位
		String def_id = info.getString("area_code","");
		String s = id.replace(def_id, "");
		int postId = Integer.parseInt(s);
		Log.i("update", "preId="+preId);
		Log.i("update", "postId="+postId);
		
		//封面
		HereTipa ht=new HereTipa(getBaseContext());
		ht.selectHereTipa(preId);
		ht.setHeti_profileid(postId);
		ht.setHeti_here_id(recordid);
		ht.updateHereTipa(preId);
		
		//基本信息表
		PersonInfo pi = new PersonInfo(getBaseContext());
		pi.selectPersonInfo(preId);
		pi.setPein_profile_id(postId);
		pi.updatePersonInfo(preId);
		
		//体检表
		HealthTest htt=new HealthTest(getBaseContext());
		htt.setHete_profileid(postId);
		htt.setHete_testid(1);//第一次体检???
		htt.insertHealthTest();
		
		//住院史---限填2项
		HospitalHistory hh = new HospitalHistory(getBaseContext());
		hh.setHohi_profileid(postId);
		hh.setHohi_testid(1);
		hh.setHohi_id(1);
		hh.insertHospitalHistory();
		hh.setHohi_profileid(postId);
		hh.setHohi_testid(1);
		hh.setHohi_id(2);
		hh.insertHospitalHistory();
		//病床史---限填2项
		SickbedHistory sh = new SickbedHistory(getBaseContext());
		sh.setSihi_profileid(postId);
		sh.setSihi_testid(1);
		sh.setSihi_id(1);
		sh.insertSickbedHistory();
		sh.setSihi_profileid(postId);
		sh.setSihi_testid(1);
		sh.setSihi_id(2);
		sh.insertSickbedHistory();
		//吃药信息---限填6项
		MedicateRecord mr = new MedicateRecord(getBaseContext());
		mr.setMere_profileid(postId);
		mr.setMere_testid(1);
		mr.setMere_id(1);
		mr.insertMedicateRecord();
		mr.setMere_profileid(postId);
		mr.setMere_testid(1);
		mr.setMere_id(2);
		mr.insertMedicateRecord();
		mr.setMere_profileid(postId);
		mr.setMere_testid(1);
		mr.setMere_id(3);
		mr.insertMedicateRecord();
		mr.setMere_profileid(postId);
		mr.setMere_testid(1);
		mr.setMere_id(4);
		mr.insertMedicateRecord();
		mr.setMere_profileid(postId);
		mr.setMere_testid(1);
		mr.setMere_id(5);
		mr.insertMedicateRecord();
		mr.setMere_profileid(postId);
		mr.setMere_testid(1);
		mr.setMere_id(6);
		mr.insertMedicateRecord();
		//非免疫预防接种---限填3项
		NonimmuneVaccineHistory nvh = new NonimmuneVaccineHistory(getBaseContext());
		nvh.setNovh_profileid(postId);
		nvh.setNovh_testid(1);
		nvh.setNovh_id(1);
		nvh.insertNonimmuneVaccineHistory();
		nvh.setNovh_profileid(postId);
		nvh.setNovh_testid(1);
		nvh.setNovh_id(2);
		nvh.insertNonimmuneVaccineHistory();
		nvh.setNovh_profileid(postId);
		nvh.setNovh_testid(1);
		nvh.setNovh_id(3);
		nvh.insertNonimmuneVaccineHistory();
		
		ModuleSelect ms=new ModuleSelect(getBaseContext());
		ms.setMose_profile_id(postId);
		ms.setMose_health_record_id(1);
		ms.insertModuleSelect();
		JieZhenRecord jzr=new JieZhenRecord(getBaseContext());
		jzr.setThre_profileid(postId);
		jzr.setThre_state(1);
		jzr.insertJieZhenRecord();
		HuiZhenRecord hzr=new HuiZhenRecord(getBaseContext());
		hzr.setCore_profileid(postId);
		hzr.setCore_state(1);
		hzr.insertHuiZhenRecord();
	}
}
